#!/usr/bin/python
# encoding: utf-8

from flask import  Flask
from flask import Flask, jsonify, render_template, request, make_response, redirect, url_for
import os
import requests
import hashlib

app=Flask(__name__)

def md5(s):
    md5s = hashlib.md5()
    md5s.update(s.encode('utf-8'))
    return md5s.hexdigest()

@app.route('/')
def index():
    url = request.args.get('url', '')
    if not url:
        return 'no url'
    response = requests.get(url, timeout=60)
    img = response.content
    im_path = '/data/temp/image.jpg'
    with open(im_path, 'wb') as f:
        f.write(img)
    out_path = f'/data/out/{md5(url)}.png'
    os.system(f'backgroundremover -i "/data/temp/image.jpg" -o "{out_path}"')
    if os.path.exists(im_path):
        os.remove(im_path)
    out_img = ''
    with open(out_path, 'rb') as f:
        out_img = f.read()
    resp = make_response(out_img)
    resp.headers['Content-type'] = 'image/png'
    return resp, 200

if __name__=="__main__":
    app.run(port=8080, host='0.0.0.0', debug=True)